<template>
    <div class="app-container">
        <div style="background-color: #ffffff;">
            <div id="container"></div>
        </div>
    </div>
</template>
 
<script setup>
import AMapLoader from '@amap/amap-jsapi-loader';
/*在Vue3中使用时,需要引入Vue3中的shallowRef方法(使用shallowRef进行非深度监听,
因为在Vue3中所使用的Proxy拦截操作会改变JSAPI原生对象,所以此处需要区别Vue2使用方式对地图对象进行非深度监听,
否则会出现问题,建议JSAPI相关对象采用非响应式的普通对象来存储)*/
// import { shallowRef } from '@vue/reactivity';
import { ref } from "vue";

///融合轨迹
const path = ref([]);
var gpsShow = true;
var gpsGroup;
var gpsTrackLine;
///mag轨迹
const mag_path = ref([]);
var magShow = false;
var magGroup;
var magTrackLine;
///lidar轨迹
const lidar_path = ref([]);
var lidarShow = false;
var lidarGroup;
var lidarTrackLine;
///gnss轨迹
const gnss_path = ref([]);
var gnssShow = false;
var gnssGroup;
var gnssTrackLine;
///antignss
const anti_path = ref([]);
var antiShow = false;
var antiGroup;
var antiTrackLine;

var polylineGroupMax = 1200;
var removePolylineCount = 600;

var carMarker;
let driving;
var isCarLine = 0; //是展示车的路线还是poi点的路径规划
const ImgUrl1 = require('../assets/poi_wei.png');

var gpsColor = '#3366FF';
var magColor = '#ff2050';
var lidarColor = '#332050';
var gnssColor = '#FFB400';
var antiColor = '#640059';


function initMap() {
    window.forceWebGL = true;
    // path.value.push([116.249413, 40.070153]);
    window._AMapSecurityConfig = {
        securityJsCode: '615a40fdd1f6a5649c8a6cc9cdd8aedd',
    }
    AMapLoader.load({
        key: "920b13e44a6e231bc980c07281279c17", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15npm
        // plugins:[''], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        const map = new AMap.Map("container", {  //设置地图容器id
            viewMode: "3D",    //是否为3D地图模式
            zoom: 16,
            zooms: [8, 20],           //初始化地图级别
            center: [116.249413, 40.070153], //初始化地图中心点位置
            animateEnable: true,
            resizeEnable: true,
        });
        // 添加插件
        AMap.plugin(["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.Geolocation", "AMap.MapType", "AMap.MouseTool", "AMap.PlaceSearch"], function () {
            //异步同时加载多个插件
            // 添加地图插件
            // map.addControl(new AMap.ToolBar()); // 工具条控件;范围选择控件
            map.addControl(new AMap.Scale()); // 显示当前地图中心的比例尺
            // map.addControl(new AMap.HawkEye()); // 显示缩略图
            map.addControl(new AMap.Geolocation()); // 定位当前位置
        });

        // 实例化点标记
        // 第一种(封成函数来触发)
        function addCarMarker(e) {
            var icon = new AMap.Icon({ size: AMap.Size(24, 24), image: require('@/assets/car.png'), imageSize: AMap.Size(24, 24), imageOffset: AMap.Pixel(0, 0) });
            const marker = new AMap.Marker({
                icon: icon,
                position: e, // 这里我们通过上面的点击获取经纬度坐标,实时添加标记
                // 通过设置 offset 来添加偏移量
                offset: new AMap.Pixel(0, 0),
                autoRotation: true,
                angle: -0,
                anchor: 'center'
            });
            marker.setMap(map);
            carMarker = marker;
            console.log('添加定位点');
        }

        function addPoiMarker(lgla, name) {

            var content =
                `<div class="poi" style="text-align:center">` +
                `<div style = "background:-webkit-gradient(linear, left center, right center, from(#fff),color-stop(20%, black),color-stop(80%, black),to(#fff)); color:#fff;white-space:nowrap;margin-bottom:5px;padding:3px">${name}</div>` +
                `<img src = '${ImgUrl1}' width='32'></img>` +
                '</div>';

            const marker = new AMap.Marker({
                position: lgla, // 这里我们通过上面的点击获取经纬度坐标,实时添加标记
                // 通过设置 offset 来添加偏移量
                offset: new AMap.Pixel(0, 0),
                autoRotation: true,
                angle: -0,
                anchor: 'center',
                content: content
            });
            marker.on('click', function (ev) {
                // 触发事件的对象
                console.log('poi marker click------规划路线！！！！！！！！！！！');
                var lnglat = ev.lnglat;
                drivingPoline([116.397455, 39.909187], lnglat);
            });
            map.add(marker);
            map.setFitView();
        }

        //折线
        // function addPolyLine(linePoints, color) {
        //     const polyline = new AMap.Polyline({
        //         path: linePoints,
        //         isOutline: true,
        //         outlineColor: "#ffeeff",
        //         borderWeight: 1,
        //         strokeColor: color,
        //         strokeOpacity: 0.6,
        //         strokeWeight: 5,
        //         // 折线样式还支持 'dashed'
        //         strokeStyle: "solid",
        //         // strokeStyle是dashed时有效
        //         // strokeDasharray: [10, 5],
        //         lineJoin: "round",
        //         lineCap: "round",
        //         zIndex: 50,
        //     });
        //     map.add([polyline]);
        //     return polyline;
        //     // map.setCenter(path.value[path.value.length - 1]);
        // }

        function addPolyLine2(linePoints, color) {
            const polyline = new AMap.Polyline({
                path: linePoints,
                isOutline: true,
                outlineColor: "#ffeeff",
                borderWeight: 1,
                strokeColor: color,
                strokeOpacity: 0.6,
                strokeWeight: 5,
                // 折线样式还支持 'dashed'
                strokeStyle: "solid",
                // strokeStyle是dashed时有效
                // strokeDasharray: [10, 5],
                lineJoin: "round",
                lineCap: "butt",
                zIndex: 50,
            });
            return polyline;
            // map.setCenter(path.value[path.value.length - 1]);
        }

        //路径规划
        function drivingPoline(start, end) {
            AMap.plugin('AMap.Driving', function () {
                if (driving == null) {
                    driving = new AMap.Driving({
                        map: map,
                        // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
                        policy: AMap.DrivingPolicy.LEAST_TIME,
                        hideMarkers: true
                    })
                }
                driving.clear();

                driving.search(start, end, function (status, result) {
                    // 未出错时，result即是对应的路线规划方案
                    console.log('搜索的路径规划======' + JSON.stringify(result));
                })
            })
        }

        //POI搜索
        const placeSearch = new AMap.PlaceSearch({
            // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
            city: '010',
            pageSize: 5, // 单页显示结果条数
            pageIndex: 1, // 页码
            citylimit: true,  //是否强制限制在设置的城市内搜索
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        })


        function clearMapOverlay() {
            carMarker = null;
            if (driving != null) {
                driving.clear();
                driving = null;
            }
            gpsTrackLine = null;
            magTrackLine = null;
            lidarTrackLine = null;
            gnssTrackLine = null;
            antiTrackLine = null;
            map.clearMap();
        }


        // addCarMarker();
        connectSocket(function (e) {
            console.log("服务器返回的信息: " + e.data);
            var jsonData = JSON.parse(e.data);
            ///信令的名字--SetStyle--Search--Location
            var name = jsonData.name;
            if (name == 'SetStyle') {
                var style = jsonData.value;
                isCarLine = style;
                clearMapOverlay();
                // if (style == 0) {
                //     //清除掉之前的路径和marker
                //     carMarker = null;
                //     if (driving != null) {
                //         driving.clear();
                //         driving = null;
                //     }
                //     map.clearMap();
                // } else if (style == 1) {

                // }
            }

            if (name == 'Search') {
                //清除掉之前的路径和marker
                carMarker = null;
                map.clearMap();
                var words = jsonData.value;
                ///触发搜索poi
                placeSearch.search(words, function (status, result) {
                    // 查询成功时，result即对应匹配的POI信息
                    var pois = result['poiList']['pois'];
                    for (let index = 0; index < pois.length; index++) {
                        const element = pois[index];
                        var loc = element.location;
                        var n = element.name;
                        console.log("poi的定位信息: " + loc);
                        addPoiMarker(loc, n);
                    }
                })
            }

            if (name == 'SetLocationType') {
                var typeN = jsonData.type;
                var typeV = jsonData.value;
                console.log("切换路线模式-  typeN----: " + typeN);
                console.log("切换路线模式-  typeV----: " + typeV);
                if (typeN == 'CarLocationType.gps') {
                    if (typeV == 1) {
                        gpsShow = true;
                        if (gpsGroup != null) {
                            gpsGroup.show();
                        }

                    } else {
                        gpsShow = false;
                        if (gpsGroup != null) {
                            gpsGroup.hide();
                        }

                    }
                }
                if (typeN == 'CarLocationType.mag') {
                    if (typeV == 1) {
                        magShow = true;
                        if (magGroup != null) {
                            magGroup.show();
                        }

                    } else {
                        magShow = false;

                        if (magGroup != null) {
                            magGroup.hide();
                        }
                    }
                }
                if (typeN == 'CarLocationType.lidar') {
                    if (typeV == 1) {
                        lidarShow = true;
                        if (lidarGroup != null) {
                            lidarGroup.show();
                        }

                    } else {
                        lidarShow = false;
                        if (lidarGroup != null) {
                            lidarGroup.hide();
                        }
                    }
                }
                if (typeN == 'CarLocationType.gnss') {

                    if (typeV == 1) {
                        gnssShow = true;
                        if (gnssGroup != null) {
                            gnssGroup.show();
                        }

                    } else {
                        gnssShow = false;
                        if (gnssGroup != null) {
                            gnssGroup.hide();
                        }
                    }
                }
                if (typeN == 'CarLocationType.antignss') {

                    if (typeV == 1) {
                        antiShow = true;

                        if (antiGroup != null) {
                            antiGroup.show();
                        }
                    } else {
                        antiShow = false;
                        if (antiGroup != null) {
                            antiGroup.hide();
                        }
                    }
                }
            }

            if (name == 'Location') {
                if (isCarLine == 0) {
                    var latitude = jsonData.latitude;
                    var longitude = jsonData.longitude;
                    var Locationtype = jsonData.type;
                    var lnglats = [longitude, latitude]; // Array.<LngLat>

                    if (Locationtype == 'CarLocationType.gps') {
                        console.log('接到CarLocationType.gps 数据！！！！！！！！！！！');
                        ///之前最后的点
                        if (path.value.length == 0) {
                            path.value.push(lnglats);
                            gpsGroup = new AMap.OverlayGroup([]);
                            map.add(gpsGroup);
                        } else {
                            var lastLnglats = path.value[path.value.length - 1];
                            path.value.push(lnglats);
                            var gpline = addPolyLine2([lastLnglats, lnglats], gpsColor);
                            gpsGroup.addOverlay(gpline);
                            path.value.shift();
                            if (gpsGroup.length >= polylineGroupMax) {
                                var frontGpsAry = gpsGroup.getOverlays();
                                gpsGroup.removeOverlays(frontGpsAry.slice(0, removePolylineCount));
                            }
                            console.log('add gpline');
                            if (!gpsShow) {
                                gpsGroup.hide();
                            }
                        }
                        if (carMarker == null) {
                            addCarMarker(lnglats);
                        }
                        carMarker.setPosition(lnglats);
                        map.setCenter(lnglats)
                    }
                    if (Locationtype == 'CarLocationType.mag') {
                        if (mag_path.value.length == 0) {
                            mag_path.value.push(lnglats);
                            magGroup = new AMap.OverlayGroup([]);
                            map.add(magGroup);
                            magGroup.hide();
                        } else {
                            var m_lastLnglats = mag_path.value[mag_path.value.length - 1];
                            mag_path.value.push(lnglats);
                            var magpline = addPolyLine2([m_lastLnglats, lnglats], magColor);
                            magGroup.addOverlay(magpline);
                            mag_path.value.shift();
                            if (magGroup.length >= polylineGroupMax) {
                                var frontMagAry = magGroup.getOverlays();
                                magGroup.removeOverlays(frontMagAry.slice(0, removePolylineCount));
                            }
                            console.log('add magpline');
                            if (!magShow) {
                                magGroup.hide();
                            }
                        }
                    }
                    if (Locationtype == 'CarLocationType.lidar') {
                        if (lidar_path.value.length == 0) {
                            lidar_path.value.push(lnglats);
                            lidarGroup = new AMap.OverlayGroup([]);
                            map.add(lidarGroup);
                            lidarGroup.hide();
                        } else {
                            var ld_lastLnglats = lidar_path.value[lidar_path.value.length - 1];
                            lidar_path.value.push(lnglats);
                            var lidarpline = addPolyLine2([ld_lastLnglats, lnglats], lidarColor);
                            lidarGroup.addOverlay(lidarpline);
                            lidar_path.value.shift();
                            if (lidarGroup.length >= polylineGroupMax) {
                                var frontLidarAry = lidarGroup.getOverlays();
                                lidarGroup.removeOverlays(frontLidarAry.slice(0, removePolylineCount));
                            }
                            console.log('add lidarpline');
                            if (!lidarShow) {
                                lidarGroup.hide();
                            }
                        }
                    }
                    if (Locationtype == 'CarLocationType.gnss') {
                        if (gnss_path.value.length == 0) {
                            gnss_path.value.push(lnglats);
                            gnssGroup = new AMap.OverlayGroup([]);
                            map.add(gnssGroup);
                            gnssGroup.hide();
                        } else {
                            var gn_lastLnglats = gnss_path.value[gnss_path.value.length - 1];
                            gnss_path.value.push(lnglats);
                            var gnspline = addPolyLine2([gn_lastLnglats, lnglats], gnssColor);
                            gnssGroup.addOverlay(gnspline);
                            gnss_path.value.shift();
                            if (gnssGroup.length >= polylineGroupMax) {
                                var frontGnssAry = gnssGroup.getOverlays();
                                gnssGroup.removeOverlays(frontGnssAry.slice(0, removePolylineCount));
                            }
                            console.log('add gnspline');
                            if (!gnssShow) {
                                gnssGroup.hide();
                            }
                        }
                    }
                    if (Locationtype == 'CarLocationType.antignss') {
                        if (anti_path.value.length == 0) {
                            anti_path.value.push(lnglats);
                            antiGroup = new AMap.OverlayGroup([]);
                            map.add(antiGroup);
                            antiGroup.hide();
                        } else {
                            var an_lastLnglats = anti_path.value[anti_path.value.length - 1];
                            anti_path.value.push(lnglats);
                            var anspline = addPolyLine2([an_lastLnglats, lnglats], antiColor);
                            antiGroup.addOverlay(anspline);
                            anti_path.value.shift();
                            if (antiGroup.length >= polylineGroupMax) {
                                var frontAntiAry = antiGroup.getOverlays();
                                antiGroup.removeOverlays(frontAntiAry.slice(0, removePolylineCount));
                            }
                            console.log('add anspline');
                            if (!antiShow) {
                                antiGroup.hide();
                            }
                        }
                    }



                }
            }
            ///绘制全程轨迹
            if (name == 'AllCoordinates') {
                var coordinateType = jsonData.type;
                var coordinateList = jsonData.value;
                var showLine = jsonData.show;
                console.log('稀疏前的坐标点数组--------'+coordinateList);
                var formatAry = getPolylinePaths(coordinateList);
                console.log('转换后的坐标点数组--------'+formatAry);

                if (coordinateType == 'CarLocationType.gps') {
                    if (gpsTrackLine != null) {
                        map.remove(gpsTrackLine);
                        gpsTrackLine = null;
                    }
                    if (showLine == 1) {
                        gpsTrackLine = addPolyLine2(formatAry, gpsColor);
                        map.add([gpsTrackLine]);
                    }
                }
                if (coordinateType == 'CarLocationType.mag') {
                    if (magTrackLine != null) {
                        map.remove(magTrackLine);
                        magTrackLine = null;
                    }
                    if (showLine == 1) {
                        magTrackLine = addPolyLine2(formatAry, magColor);
                        map.add([magTrackLine]);
                    }
                }
                if (coordinateType == 'CarLocationType.lidar') {
                    if (lidarTrackLine != null) {
                        map.remove(lidarTrackLine);
                        lidarTrackLine = null;
                    }
                    if (showLine == 1) {
                        lidarTrackLine = addPolyLine2(formatAry, lidarColor);
                        map.add([lidarTrackLine]);
                    }
                }
                if (coordinateType == 'CarLocationType.gnss') {
                    if (gnssTrackLine != null) {
                        map.remove(gnssTrackLine);
                        gnssTrackLine = null;
                    }
                    if (showLine == 1) {
                        gnssTrackLine = addPolyLine2(formatAry, gnssColor);
                        map.add([gnssTrackLine]);
                    }
                }
                if (coordinateType == 'CarLocationType.antignss') {
                    if (antiTrackLine != null) {
                        map.remove(antiTrackLine);
                        antiTrackLine = null;
                    }
                    if (showLine == 1) {
                        antiTrackLine = addPolyLine2(formatAry, antiColor);
                        map.add([antiTrackLine]);
                    }
                }
            }
        });

        function getPolylinePaths(e) {
            var coorPath = [];
            e.forEach(element => {
                console.log('坐标数组元素------'+element);
                var corStr = element.split(',');
                console.log('坐标数组元素分隔符------'+corStr);
                coorPath.push([corStr[0], corStr[1]]);
            });
            return coorPath;
        }

    }).catch(e => {
        console.log(e);
    })


}

function connectSocket(onmessage) {

    console.log('准备 websocket')
    // 1.建立链接 -- 携带cookie参数
    var ws = new WebSocket(
        'ws://127.0.0.1:10800'
    );
    ws.onmessage = onmessage;
    ws.onerror = function () {
        console.log('websocket error----重启ws');
        connectSocket(onmessage);
    };
    ws.onclose = function () {
        console.log('websocket onclose----重启ws');
        connectSocket(onmessage);
    };
}



try {
    initMap()
} catch (error) {
    console.log('地图log' + error.message)
}


</script>
 
<style>
#container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 100vh;
}
</style>